package gui.view;

import generated.domain.world.World;
import gui.action.OpenWorldMapEditorAction;

import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.ViewPart;

import vworld.Client;

public class IntroView extends ViewPart {
	public static final String ID = "gui.view.IntroView";
	private ListViewer worldsViewer;

	@Override
	public void createPartControl(Composite parent) {
		worldsViewer = new ListViewer(parent, SWT.BORDER);
		worldsViewer.setLabelProvider(new ListLabelProvider());
		worldsViewer.setContentProvider(new ContentProvider());
		worldsViewer.setInput(createModel());

		hookDoubleClickAction();
	}

	private Object createModel() {
		return Client.WORLD_SERVICE.getWorlds();
	}

	@Override
	public void setFocus() {
		worldsViewer.getControl().setFocus();
	}

	class ContentProvider implements IStructuredContentProvider {
		public void dispose() {
		}

		public Object[] getElements(Object inputElement) {
			return (World[]) inputElement;
		}

		public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
		}
	}

	class ListLabelProvider extends LabelProvider {
		@Override
		public Image getImage(Object element) {
			return null;
		}

		@Override
		public String getText(Object element) {
			return ((World) element).name;
		}
	}

	private void hookDoubleClickAction() {
		worldsViewer.addDoubleClickListener(new IDoubleClickListener() {
			public void doubleClick(DoubleClickEvent event) {
				IStructuredSelection selection = (IStructuredSelection) event
						.getSelection();
				if (!selection.isEmpty()) {
					Object object = selection.getFirstElement();
					if (object instanceof World) {
						Client.CURRENT_WORLD = (World) object;
						OpenWorldMapEditorAction
								.openEditor(Client.CURRENT_WORLD);
					}
				}
			}
		});
	}
}